package com.zwh.chatgpt.test.domain.ai.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zwh.chatgpt.test.domain.ai.IOpenAI;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;

@Service
public class OpenAI implements IOpenAI {

    private Logger logger = LoggerFactory.getLogger(OpenAI.class);

    @Value("${chatgpt-ai.doubaokey}")
    private String doubaokey;

    @Override
    public String doDouBao(String question) throws IOException, InterruptedException {

        // 创建HttpClient实例
        HttpClient client = HttpClient.newBuilder()
                .version(HttpClient.Version.HTTP_1_1)
                .connectTimeout(Duration.ofSeconds(20))
                .build();

        // 请求URL
        String post = "https://ark.cn-beijing.volces.com/api/v3/chat/completions";

        // 请求体JSON
        String paramJson = "{"
                + "\"model\": \"doubao-1-5-thinking-pro-250415\","
                + "\"messages\": ["
                + "    {\"role\": \"system\", \"content\": \"你要回答得简洁明了一些\"},"
                + "    {\"role\": \"user\", \"content\": \"" + question + "\"}"
                + "]}";//sys是相当于对后台系统的暗示，user的就是表面要回答的问题

        // 构建HTTP请求
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(post))
                .timeout(Duration.ofSeconds(40))
                .header("Content-Type", "application/json")
                .header("Authorization", "Bearer " + doubaokey)
                .POST(HttpRequest.BodyPublishers.ofString(paramJson))
                .build();

        // 发送请求并获取响应
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

        // 解析响应并提取回答内容!!!!!!!
        return parseDoubaoAnswer(response.body());
    }

    private String parseDoubaoAnswer(String responseJson) {
        try {
            // 将JSON字符串转为JSONObject
            JSONObject obj = JSON.parseObject(responseJson);
            // 提取choices数组中的第一个元素的message.content
            return obj.getJSONArray("choices")
                    .getJSONObject(0)
                    .getJSONObject("message")
                    .getString("content")
                    .trim();
        } catch (Exception e) {
            logger.error("解析豆包响应失败，原始数据：{}", responseJson, e);
            throw new RuntimeException("回答解析失败");
        }
    }
}